import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { NextRequest } from 'next/server';
import * as fs from 'fs';
import * as path from 'path';
import { v4 as uuidv4 } from 'uuid';

// 确保上传目录存在
const uploadDir = 'D:\\upload';
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

// 静态文件访问的基础URL
const staticBaseUrl = 'http://localhost:3000/upload';

export async function GET() {
  try {
    // 从数据库获取所有轮播图
    const carousels = await prisma.carousel.findMany();
    return NextResponse.json({ carousels }, { status: 200 });
  } catch (error) {
    console.error('获取轮播图数据失败:', error);
    return NextResponse.json(
      { error: '获取轮播图数据失败' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const formData = await request.formData();
    const imageFile = formData.get('image') as File | null;
    const hyperlink = formData.get('hyperlink') as string | null;
    
    let imageUrl = null;
    
    // 处理图片上传
    if (imageFile) {
      const bytes = await imageFile.arrayBuffer();
      const buffer = Buffer.from(bytes);
      
      // 生成唯一文件名
      const fileName = `${uuidv4()}_${imageFile.name}`;
      const filePath = path.join(uploadDir, fileName);
      
      // 写入文件
      fs.writeFileSync(filePath, buffer);
      
      // 生成访问URL (使用绝对路径，便于小程序访问)
      // 保存绝对磁盘路径到数据库
      imageUrl = filePath;
      
      console.log(`图片已上传到: ${imageUrl}`);
    }
    
    // 创建轮播图记录
    const carousel = await prisma.carousel.create({
      data: {
        imageUrl,
        hyperlink
      }
    });
    
    return NextResponse.json({ carousel }, { status: 201 });
  } catch (error) {
    console.error('创建轮播图失败:', error);
    return NextResponse.json(
      { error: '创建轮播图失败' },
      { status: 500 }
    );
  }
}